import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Progress } from './ui/progress';
import { Badge } from './ui/badge';
import { Palette, Timer, Target, RotateCcw, Eye, CheckCircle } from 'lucide-react';

interface TestResult {
  testType: string;
  score: number;
  details: string;
  timestamp: Date;
}

interface ColorTestProps {
  onComplete: (result: TestResult) => void;
}

type TestState = 'ready' | 'testing' | 'complete';

interface ColorChallenge {
  id: number;
  displayColor: string;
  displayColorName: string;
  wordMeaning: string;
  isCongruent: boolean;
  userAnswer?: string;
  isCorrect?: boolean;
  responseTime?: number;
}

const colors = [
  { name: '红色', value: '#ef4444' },
  { name: '蓝色', value: '#3b82f6' },
  { name: '绿色', value: '#10b981' },
  { name: '黄色', value: '#f59e0b' },
  { name: '紫色', value: '#8b5cf6' },
  { name: '橙色', value: '#f97316' },
  { name: '粉色', value: '#ec4899' },
  { name: '青色', value: '#06b6d4' }
];

export function ColorTest({ onComplete }: ColorTestProps) {
  const [state, setState] = useState<TestState>('ready');
  const [challenges, setChallenges] = useState<ColorChallenge[]>([]);
  const [currentChallenge, setCurrentChallenge] = useState<ColorChallenge | null>(null);
  const [currentIndex, setCurrentIndex] = useState(0);
  const [startTime, setStartTime] = useState<number>(0);
  const [scores, setScores] = useState({ correct: 0, incorrect: 0 });

  const totalChallenges = 20;

  const generateChallenge = useCallback(() => {
    const isCongruent = Math.random() > 0.5;
    const displayColor = colors[Math.floor(Math.random() * colors.length)];
    const wordMeaning = isCongruent 
      ? displayColor.name 
      : colors.filter(c => c.name !== displayColor.name)[Math.floor(Math.random() * (colors.length - 1))].name;
    
    const challenge: ColorChallenge = {
      id: Date.now() + Math.random(),
      displayColor: displayColor.value,
      displayColorName: displayColor.name,
      wordMeaning: wordMeaning,
      isCongruent
    };
    
    return challenge;
  }, []);

  const startTest = useCallback(() => {
    setState('testing');
    setCurrentIndex(0);
    setScores({ correct: 0, incorrect: 0 });
    
    const newChallenges = Array.from({ length: totalChallenges }, generateChallenge);
    setChallenges(newChallenges);
    setCurrentChallenge(newChallenges[0]);
    setStartTime(Date.now());
  }, [generateChallenge]);

  const handleAnswer = (selectedColorName: string) => {
    if (!currentChallenge) return;
    
    const responseTime = Date.now() - startTime;
    // In Stroop test, correct answer is always the display color, not the word meaning
    const isCorrect = selectedColorName === currentChallenge.displayColorName;
    
    const updatedChallenge = {
      ...currentChallenge,
      userAnswer: selectedColorName,
      isCorrect,
      responseTime
    };
    
    setChallenges(prev => prev.map(c => 
      c.id === currentChallenge.id ? updatedChallenge : c
    ));
    
    setScores(prev => ({
      correct: prev.correct + (isCorrect ? 1 : 0),
      incorrect: prev.incorrect + (isCorrect ? 0 : 1)
    }));

    // Move to next challenge
    const nextIndex = currentIndex + 1;
    if (nextIndex >= totalChallenges) {
      setState('complete');
    } else {
      setCurrentIndex(nextIndex);
      setCurrentChallenge(challenges[nextIndex]);
      setStartTime(Date.now());
    }
  };

  const resetTest = () => {
    setState('ready');
    setChallenges([]);
    setCurrentChallenge(null);
    setCurrentIndex(0);
    setScores({ correct: 0, incorrect: 0 });
  };

  const getAccuracy = () => {
    const total = scores.correct + scores.incorrect;
    return total > 0 ? Math.round((scores.correct / total) * 100) : 0;
  };

  const getAverageResponseTime = () => {
    const completedChallenges = challenges.filter(c => c.responseTime);
    if (completedChallenges.length === 0) return 0;
    
    const totalTime = completedChallenges.reduce((sum, c) => sum + (c.responseTime || 0), 0);
    return Math.round(totalTime / completedChallenges.length);
  };

  const getCongruencyStats = () => {
    const congruentChallenges = challenges.filter(c => c.isCongruent && c.isCorrect !== undefined);
    const incongruentChallenges = challenges.filter(c => !c.isCongruent && c.isCorrect !== undefined);
    
    const congruentAccuracy = congruentChallenges.length > 0 
      ? Math.round((congruentChallenges.filter(c => c.isCorrect).length / congruentChallenges.length) * 100)
      : 0;
    
    const incongruentAccuracy = incongruentChallenges.length > 0
      ? Math.round((incongruentChallenges.filter(c => c.isCorrect).length / incongruentChallenges.length) * 100)
      : 0;
    
    return { congruentAccuracy, incongruentAccuracy };
  };

  const getFinalScore = () => {
    const accuracy = getAccuracy();
    const avgResponseTime = getAverageResponseTime();
    const { congruentAccuracy, incongruentAccuracy } = getCongruencyStats();
    
    // Base score from accuracy
    let score = accuracy;
    
    // Speed bonus (faster response = higher score)
    const speedBonus = Math.max(0, (2000 - avgResponseTime) / 2000) * 15;
    score += speedBonus;
    
    // Consistency bonus (better performance on incongruent trials shows good cognitive control)
    const stroopEffect = Math.max(0, congruentAccuracy - incongruentAccuracy);
    const controlBonus = Math.max(0, (15 - stroopEffect) / 15) * 10;
    score += controlBonus;
    
    return Math.min(100, Math.max(0, Math.round(score)));
  };

  const getRating = () => {
    const score = getFinalScore();
    if (score >= 90) return { text: '色彩大师', color: 'text-yellow-500' };
    if (score >= 80) return { text: '优秀', color: 'text-green-500' };
    if (score >= 70) return { text: '良好', color: 'text-blue-500' };
    if (score >= 60) return { text: '一般', color: 'text-gray-500' };
    return { text: '需要提高', color: 'text-orange-500' };
  };

  const handleComplete = () => {
    const result: TestResult = {
      testType: '颜色识别测试',
      score: getFinalScore(),
      details: `准确率 ${getAccuracy()}%, 平均反应时间 ${getAverageResponseTime()}ms, 完成 ${challenges.filter(c => c.isCorrect !== undefined).length} 题`,
      timestamp: new Date()
    };
    onComplete(result);
  };

  if (state === 'complete') {
    const rating = getRating();
    const { congruentAccuracy, incongruentAccuracy } = getCongruencyStats();
    
    return (
      <div className="max-w-2xl mx-auto space-y-6">
        <Card>
          <CardHeader className="text-center">
            <CardTitle className="flex items-center justify-center gap-2">
              <CheckCircle className="w-6 h-6 text-pink-500" />
              测试完成！
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-6">
            <div className="text-center space-y-4">
              <div className="text-6xl font-bold text-primary">
                {getFinalScore()}
              </div>
              <div className={`text-xl font-semibold ${rating.color}`}>
                {rating.text}
              </div>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
                <div className="text-2xl font-bold text-green-600">{scores.correct}</div>
                <div className="text-sm text-muted-foreground">正确</div>
              </div>
              <div className="text-center p-4 bg-red-50 dark:bg-red-950 rounded-lg">
                <div className="text-2xl font-bold text-red-600">{scores.incorrect}</div>
                <div className="text-sm text-muted-foreground">错误</div>
              </div>
              <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div className="text-2xl font-bold text-blue-600">{getAccuracy()}%</div>
                <div className="text-sm text-muted-foreground">准确率</div>
              </div>
              <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
                <div className="text-2xl font-bold text-purple-600">{getAverageResponseTime()}ms</div>
                <div className="text-sm text-muted-foreground">平均反应时间</div>
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-xl font-bold">{congruentAccuracy}%</div>
                <div className="text-sm text-muted-foreground">一致性测试准确率</div>
                <div className="text-xs text-muted-foreground mt-1">颜色与文字一致</div>
              </div>
              <div className="text-center p-4 bg-muted rounded-lg">
                <div className="text-xl font-bold">{incongruentAccuracy}%</div>
                <div className="text-sm text-muted-foreground">冲突性测试准确率</div>
                <div className="text-xs text-muted-foreground mt-1">颜色与文字不一致</div>
              </div>
            </div>

            <div className="space-y-2">
              <h3 className="font-semibold">详细分析</h3>
              <div className="text-sm text-muted-foreground space-y-1">
                <p>• 完成了 {challenges.filter(c => c.isCorrect !== undefined).length} 道测试题</p>
                <p>• 一致性题目准确率：{congruentAccuracy}%</p>
                <p>• 冲突性题目准确率：{incongruentAccuracy}%</p>
                <p>• Stroop效应：{Math.max(0, congruentAccuracy - incongruentAccuracy)}%</p>
                <p>• 平均反应时间：{getAverageResponseTime()}毫秒</p>
                {incongruentAccuracy < congruentAccuracy - 15 && (
                  <p className="text-orange-600">• 建议：加强认知控制能力训练</p>
                )}
                {incongruentAccuracy >= congruentAccuracy - 5 && (
                  <p className="text-green-600">• 优秀：认知控制能力很强，抗干扰能力出色</p>
                )}
              </div>
            </div>

            <div className="flex gap-4">
              <Button 
                onClick={resetTest} 
                variant="outline" 
                className="flex-1 border-2 border-slate-300 hover:border-slate-400 hover:bg-slate-50 text-slate-700 hover:text-slate-800 shadow-sm hover:shadow-md transition-all duration-300"
              >
                <RotateCcw className="w-4 h-4 mr-2" />
                重新测试
              </Button>
              <Button 
                onClick={handleComplete} 
                className="flex-1 bg-gradient-to-r from-pink-500 to-purple-600 hover:from-pink-600 hover:to-purple-700 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0"
              >
                <CheckCircle className="w-4 h-4 mr-2" />
                保存结果
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-6">
      {state === 'testing' && (
        <Card>
          <CardContent className="pt-6">
            <div className="flex justify-between items-center mb-2">
              <span className="text-sm">进度</span>
              <span className="text-sm">{currentIndex + 1}/{totalChallenges}</span>
            </div>
            <Progress value={((currentIndex + 1) / totalChallenges) * 100} />
          </CardContent>
        </Card>
      )}

      <Card>
        {state === 'ready' && (
          <>
            <CardHeader className="text-center">
              <CardTitle className="flex items-center justify-center gap-2">
                <Palette className="w-6 h-6 text-pink-500" />
                颜色识别测试（Stroop测试）
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="text-center space-y-4">
                <p className="text-muted-foreground">
                  这是经典的Stroop测试，用于测试您的认知控制能力和注意力。
                </p>
                <div className="space-y-4">
                  <div className="p-4 bg-muted rounded-lg">
                    <h3 className="font-semibold mb-2">测试规则</h3>
                    <div className="text-sm text-muted-foreground space-y-2">
                      <p>• <strong>始终选择文字的显示颜色</strong>，忽略文字本身的含义</p>
                      <p>• 这是经典的Stroop测试，测试认知控制能力</p>
                      <p>• 当颜色与文字含义冲突时，大脑需要抑制干扰</p>
                      <p>• 快速准确地识别颜色可以获得更高分数</p>
                    </div>
                  </div>
                  
                  <div className="grid grid-cols-2 gap-4">
                    <div className="text-center p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                      <div className="text-lg font-bold" style={{ color: '#10b981' }}>绿色</div>
                      <div className="text-xs text-muted-foreground mt-1">颜色一致 → 选择"绿色"</div>
                    </div>
                    <div className="text-center p-3 bg-red-50 dark:bg-red-950 rounded-lg">
                      <div className="text-lg font-bold" style={{ color: '#ef4444' }}>蓝色</div>
                      <div className="text-xs text-muted-foreground mt-1">颜色冲突 → 选择"红色"</div>
                    </div>
                  </div>
                </div>
              </div>
              <div className="text-center">
                <Button 
                  size="lg" 
                  onClick={startTest}
                  className="bg-gradient-to-r from-slate-400 to-gray-500 hover:from-slate-500 hover:to-gray-600 text-white shadow-lg hover:shadow-xl transform hover:scale-105 transition-all duration-300 border-0 min-w-[140px] h-12"
                >
                  <Palette className="w-5 h-5 mr-2" />
                  开始测试
                </Button>
              </div>
            </CardContent>
          </>
        )}

        {state === 'testing' && currentChallenge && (
          <CardContent className="space-y-8">
            <div className="text-center space-y-6">
              <div className="text-sm text-muted-foreground">
                请选择这个文字的<strong>显示颜色</strong>（忽略文字含义）
              </div>
              
              {/* The word displayed in the display color */}
              <div 
                className="text-8xl font-bold select-none"
                style={{ color: currentChallenge.displayColor }}
              >
                {currentChallenge.wordMeaning}
              </div>

              <div className="text-xs text-muted-foreground">
                {currentChallenge.isCongruent ? '颜色与文字含义一致' : '颜色与文字含义不一致'}
              </div>
            </div>

            {/* Color selection buttons */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {colors.slice(0, 4).map((color) => (
                <Button 
                  key={color.name}
                  size="lg" 
                  variant="outline"
                  onClick={() => handleAnswer(color.name)}
                  className="h-16 text-base border-2 hover:shadow-lg transition-all duration-300 flex flex-col items-center justify-center gap-1 hover:scale-105"
                  style={{
                    borderColor: color.value + '50',
                    backgroundColor: color.value + '10'
                  }}
                >
                  <div 
                    className="w-6 h-6 rounded-full border-2 border-white shadow-sm"
                    style={{ backgroundColor: color.value }}
                  />
                  <div className="text-sm font-medium" style={{ color: color.value }}>
                    {color.name}
                  </div>
                </Button>
              ))}
            </div>
            
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              {colors.slice(4).map((color) => (
                <Button 
                  key={color.name}
                  size="lg" 
                  variant="outline"
                  onClick={() => handleAnswer(color.name)}
                  className="h-16 text-base border-2 hover:shadow-lg transition-all duration-300 flex flex-col items-center justify-center gap-1 hover:scale-105"
                  style={{
                    borderColor: color.value + '50',
                    backgroundColor: color.value + '10'
                  }}
                >
                  <div 
                    className="w-6 h-6 rounded-full border-2 border-white shadow-sm"
                    style={{ backgroundColor: color.value }}
                  />
                  <div className="text-sm font-medium" style={{ color: color.value }}>
                    {color.name}
                  </div>
                </Button>
              ))}
            </div>

            {/* Real-time stats */}
            <div className="grid grid-cols-3 gap-4 text-center">
              <div className="p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                <div className="text-lg font-bold text-green-600">{scores.correct}</div>
                <div className="text-xs text-muted-foreground">正确</div>
              </div>
              <div className="p-3 bg-red-50 dark:bg-red-950 rounded-lg">
                <div className="text-lg font-bold text-red-600">{scores.incorrect}</div>
                <div className="text-xs text-muted-foreground">错误</div>
              </div>
              <div className="p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
                <div className="text-lg font-bold text-blue-600">{getAccuracy()}%</div>
                <div className="text-xs text-muted-foreground">准确率</div>
              </div>
            </div>
          </CardContent>
        )}
      </Card>

      <Card>
        <CardContent className="pt-6">
          <h3 className="font-semibold mb-2">测试说明</h3>
          <ul className="text-sm text-muted-foreground space-y-1">
            <li>• 这是经典的Stroop认知测试</li>
            <li>• 测试您的认知控制和抗干扰能力</li>
            <li>• 共有 {totalChallenges} 道测试题</li>
            <li>• 始终选择文字的显示颜色，忽略文字含义</li>
            <li>• 快速准确的反应能获得更高分数</li>
            <li>• 冲突情况下的表现反映认知控制能力</li>
          </ul>
        </CardContent>
      </Card>
    </div>
  );
}